<template>
  <biz-search-customer-select
    :value="relationCustomerValue"
    :placeholder="$t('common.form.placeHolder.relatedCustomers.pla1', {module:$t('common.base.customer')})"
    :remote-method="remoteMethod"
    @input="updateData"
    :multiple="true"
  >
  </biz-search-customer-select>
</template>

<script>
/** mixin */
import FormMixin from '@src/component/form/mixin/form';
import { getCustomerList } from '@src/api/CustomerApi'

import _ from 'lodash';

export default {
  name: 'form-related-customers',
  mixins: [FormMixin],
  props: {
    value: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      relationCustomerValue: [], // 客户联系人绑定的值
    };
  },
	mounted() {
    this.init(this.value);
	},
  watch: {
    value: {
      handler(newValue) {
        this.init(newValue);
      }
    }
  },
  methods: {
    init(val) {
      if(val && val.length > 0) {
        let relationCustomerValue = _.cloneDeep(val);
        this.relationCustomerValue = relationCustomerValue.map(item => {
          item.value = item.id;
          item.label = item.name
          return item;
        });
      }
    },
    /**
     * @description 搜索
     */
    remoteMethod(params = {}) {
      return getCustomerList(params)
        .then(res => {
          if (!res || !res.list) return;
          if (res.list) {
            res.list = res.list.map(customer =>
              Object.freeze({
                label: customer.name,
                value: customer.id,
                ...customer,
              })
            );
          }
        
          return res;
        })
        .catch(e => console.error(e));
    },
    // 关联客户更新数据
    updateData(value) {
      this.relationCustomerValue = value;
      this.inputForValue(value.map(item => {
        return {
          id: item.id,
          name: item.name
        }
      }));
    },
  },
};
</script>

<style lang="scss" scoped>
</style>
